import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
  RouteRecordRaw,
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';

import { ElMessage } from 'element-plus';

import { getPermission } from '#/api';
import { BasicLayout, IFrameView } from '#/layouts';
import { $t } from '#/locales';

import { accessRoutes } from './routes/index';

interface DataItem {
  id: number;
  delete: number;
  edit: number;
  read: number;
}

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

function filterRoutes(
  routes: RouteRecordRaw[],
  ids: Array<number>,
): RouteRecordRaw[] {
  return routes
    .map((route: any) => {
      // 先创建当前项的副本
      const filteredRoute = { ...route };
      // 如果存在 children，则递归处理
      if (filteredRoute.children) {
        filteredRoute.children = filterRoutes(
          filteredRoute.children.filter(
            (child: any) =>
              child.meta?.menuVisible || ids.includes(child.meta.id),
          ),
          ids,
        );
      }
      return filteredRoute;
    })
    .filter((route: any) => {
      return (
        route.meta?.menuVisible === true ||
        ids.includes(route.meta?.id) ||
        (route.children && route.children.length > 0)
      );
    });
}

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  };

  const accessStore = useAccessStore();
  const userStore = useUserStore();
  return await generateAccessible(preferences.app.accessMode, {
    ...options,
    fetchMenuListAsync: async () => {
      ElMessage({
        duration: 1500,
        message: `${$t('common.loadingMenu')}...`,
      });

      const powerList: DataItem[] = (await getPermission()) || [];
      // console.log('powerList', powerList);
      const result: string[] = powerList.flatMap(({ id, ...actions }) =>
        Object.entries(actions)
          .filter(([_, value]) => value === 1)
          .map(([key]) => `${id}_${key}`),
      );
      userStore.setUserInfo(
        JSON.parse(<string>localStorage.getItem('userInfo')),
      );
      accessStore.setAccessCodes(result);
      const permissions = powerList.map((item: any) => item.id);
      return new Promise<any[]>((resolve) => {
        const r = filterRoutes(accessRoutes, permissions);
        resolve(r);
      });
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  });
}

export { generateAccess };
